import React from 'react';
import { Pagination } from 'antd';
import { WeaAvatar, WeaCheckbox, WeaNewScroll, WeaLocaleProvider } from 'ecCom';
import '../../style/peopleList.less';

const getLabel = WeaLocaleProvider.getLabel;

/*
* 参数属性：
*
*  data           // 数据 【array】
*  onSelect       // 选择事件回调 【function】
*  selectedKeys   // 受控数据 【array】
*  isSingle       // 是否单选 【boolean】默认：false
*  rowSelect      // 是否点击整行选中 【boolean】默认：false
*  checkbox       // 是否有check框 【boolean】默认：true
*  scrollHeight   // 滚动条高度【非必填 number】不传参将默认适应组件本身高度（需要自己设定组件高度）
*  pageable       是否开启分页 【boolean】默认：false
*  pageParam      分页相关的配置【object】格式见下方
*  pageChange     页码改变的回调
*  className
*  style
*
* data: {
*     id: "",           // 【必需 string】 唯一标识
*     img: "",          // 【必需 string】 头像。有则提供，无则空字符串
*     name: "",         // 【必需 string】 名称 - 第一行
*     desc1: "",        // 【必需 string】 描述信息 - 第二行
*     desc2: "",        // 【非必需 string】 描述信息 - 第三行。三行文字和两行文字的样式不一样
*     type: "",         // 【非必需 用于头像 string】 如果type为group，可以更好地适配头像
*     sex: "",          // 【非必需 用于头像 string】 "0"男, "1"女。如果没有该信息则为空字符串
* }
*
* pageParam: {
*     style    【必需 number】分页样式。可选值：0, 1
*     count    【必需 number】总数
*     pageSize 【必需 number】每页数据量
*     default  【必需 number】初始页码
* }
*
* */

class WeaDocPeopleList extends React.Component {
   static defaultProps = {
      onSelect: null,
      data: [],
      selectedKeys: [],
      isSingle: false, // 是否单选
      rowSelect: false, // 是否点击整行选择
      checkbox: true, // 是否有check框
      pageable: false, // 是否开启分页
      pageParam: {
         style: 0,
         count: 0,
         pageSize: 0,
         defaultCurrent: 1,
      },
   };


   // onSelect事件回调
   selectHandle = (key) => {
      const { onSelect, selectedKeys } = this.props;
      const current = { id: key, prev: selectedKeys.includes(key) };
      const newSelect = this.selectionLogic(key, selectedKeys);
      typeof onSelect === 'function' && onSelect(newSelect, current); // 传参：最新的selectedKeys, 当前操作的key及操作前的选中状态
   };

   // 处理选中逻辑
   selectionLogic = (key, oldSelect) => {
      const { isSingle } = this.props;

      const index = oldSelect.indexOf(key);
      let newSelect;
      // 多选逻辑
      const multipleSelection = () => {
         newSelect = [...oldSelect];
         index > -1 && newSelect.splice(index, 1);
         index === -1 && newSelect.push(key);
      };
      // 单选逻辑
      const singleSelection = () => {
         if (oldSelect.includes(key)) {
            newSelect = [];
         } else {
            newSelect = [key];
         }
      };

      isSingle && singleSelection();
      !isSingle && multipleSelection();
      return newSelect;
   };

   // pageChange回调
   pageChange = (page) => {
      const { pageable, pageChange } = this.props;
      pageable && typeof pageChange === 'function' && pageChange(page);
   };

   render() {
      const { data, selectedKeys, rowSelect, checkbox, scrollHeight, pageable, pageParam, className, style } = this.props;

      return (
         <div className={`WeaDoc-PeopleList ${rowSelect ? 'row' : ''} ${className || ''} `} style={style}>
            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@qscsjx`} height={typeof scrollHeight === 'number' ? scrollHeight : null} style={{ height: pageable ? 'calc(100% - 35px)' : '100%' }}>
               <ul>
                  {
                     data.length > 0
                     ?
                        data.map(i => (
                           <PeopleItem ecId={`${this && this.props && this.props.ecId || ''}_PeopleItem@pi33mc@${i.id}`}
                             key={i.id}
                             data={i}
                             onSelect={this.selectHandle}
                             selected={selectedKeys.includes(i.id)}
                             rowSelect={rowSelect}
                             checkbox={checkbox}
                           />
                        ))
                     :
                        <div className="noData"><i className="anticon anticon-frown" />{getLabel(83553, '暂无数据')}</div>
                  }
               </ul>
            </WeaNewScroll>
            {
               pageable ?
                  <div className="people-pagination">
                     {
                        pageParam.style === 0
                           ?
                           <Pagination ecId={`${this && this.props && this.props.ecId || ''}_Pagination@bq06oi`}
                             defaultCurrent={pageParam.defaultCurrent}
                             showQuickJumper
                             total={pageParam.count}
                             pageSize={pageParam.pageSize}
                             showTotal={c => getLabel(509103, '共{total}条').replace('{total}', c)}
                             onChange={this.pageChange}
                           />
                           :
                        pageParam.style === 1
                           ?
                           <MyPagination ecId={`${this && this.props && this.props.ecId || ''}_MyPagination@dv0orx`}
                             defaultCurrent={pageParam.defaultCurrent}
                             showQuickJumper
                             total={pageParam.count}
                             pageSize={pageParam.pageSize}
                             pageChange={this.pageChange}
                           />
                           :
                           null
                     }
                  </div>

               : null
            }
         </div>
      );
   }
}


class PeopleItem extends React.Component {
   // 行选中
   rowSelect = (e) => {
      const { onSelect, data, rowSelect } = this.props;
      const flag = this.isCheck(e); // 如果点击的是check框，就不在此触发
      !flag && rowSelect && typeof onSelect === 'function' && onSelect(data.id);
   };
   // 检查点击的时候是check框
   isCheck = (e) => {
      let flag = false;
      e.target.tagName === 'INPUT' && (flag = true);
      return flag;
   };

   // checkbox选中
   checkBoxSelect = () => {
      const { onSelect, data } = this.props;
      typeof onSelect === 'function' && onSelect(data.id);
   };

   render() {
      const { data, selected, rowSelect, checkbox } = this.props;
      const { type, img, name, sex, desc1, desc2 } = data;
      return (
         <li className={`WeaDoc-PeopleItem ${rowSelect && selected ? 'active' : ''}${desc2 ? '' : ' twoRow'}`}
           onClick={this.rowSelect}
         >
            { checkbox ? <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@5pdtug`} value={selected ? '1' : '0'} onChange={this.checkBoxSelect} /> : null }
            <WeaAvatar ecId={`${this && this.props && this.props.ecId || ''}_WeaAvatar@kv9pf0`} url={img} name={name} type="2" gender={sex || ''} isGroup={type === 'group'} />
            <div className="content">
               <div>{name}</div>
               <div className="desc">{ desc1 }</div>
               { desc2 ? <div className="desc">{ desc2 }</div> : null }
               { !checkbox && selected ? <i className="icon-coms-complete" /> : null }
            </div>
         </li>
      );
   }
}

// 自定义分页样式
class MyPagination extends React.Component {
   static defaultProps = {
      total: 0,
      pageSize: 0,
      defaultCurrent: 1,
   };

   constructor(props) {
      super(props);
      const { total, defaultCurrent, pageSize } = this.props;
      this.state = {
         current: defaultCurrent,
         max: Math.ceil(total / pageSize),
      };
   }

   static getDerivedStateFromProps(nextProps, prevState) {
      // max
      const { total, pageSize } = nextProps;
      let max = Math.ceil(total / pageSize);
      if (max === prevState.max) {
         return null;
      }
         return { max };
   }

   // pageChange回调
   onChange = (type) => {
      const { pageChange } = this.props;
      const { current, max } = this.state;
      let now = current;
      switch (type) {
         case 'first':
            current > 1 && (now = 1);
            break;
         case 'prev':
            current > 1 && (now = current - 1);
            break;
         case 'next':
            current < max && (now = current + 1);
            break;
         case 'last':
            current < max && (now = max);
            break;
         default:
            break;
      }
      this.setState({ current: now });
      typeof pageChange === 'function' && pageChange(now);
   };

   render() {
      const { current, max } = this.state;
      const { total } = this.props;

      return (
         <ul className="My-Pagination">
            <span className="ant-pagination-total-text">{ getLabel(509103, '共{total}条').replace('{total}', total) }</span>
            <li title="第一页"
              className={`ant-pagination-first${current === 1 ? ' ant-pagination-disabled' : ''}`}
              onClick={() => {
 this.onChange('first'); 
}}
            ><a /></li>
            <li title="上一页"
              className={`ant-pagination-prev${current === 1 ? ' ant-pagination-disabled' : ''}`}
              onClick={() => {
 this.onChange('prev'); 
}}
            ><a /></li>
            <div title="1/2" className="ant-pagination-weaSimple-pager">
               <span className="ant-pagination-current">{ getLabel(15323, '第') === '第' ? '第' : 'Page' } {current}</span>
               <span className="ant-pagination-slash">／</span>
               {max}{ getLabel(30642, '页') === '页' ? '页' : null }
            </div>
            <li title="下一页"
              className={`ant-pagination-next${current === max ? ' ant-pagination-disabled' : ''}`}
              onClick={() => {
 this.onChange('next'); 
}}
            ><a /></li>
            <li title="最后一页"
              className={`ant-pagination-last${current === max ? ' ant-pagination-disabled' : ''}`}
              onClick={() => {
 this.onChange('last'); 
}}
            ><a /></li>
         </ul>
      );
   }
}


export default WeaDocPeopleList;
